package logic

import (
	"context"
	"errors"
	"gitee.com/yumo01/weikang-srv/internal/svc"
	"gitee.com/yumo01/weikang-srv/weikang"
	"github.com/15733012783/weikang/model/mysql"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *weikang.User) (*weikang.User, error) {
	var u weikang.User
	mysql.InItMysql(func(db *gorm.DB) (interface{}, error) {
		err := db.Table("users").Where("username=?", in.Name).First(&u).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return nil, status.Errorf(codes.NotFound, "该用户不存在"+err.Error())
			} else {
				return nil, status.Errorf(codes.FailedPrecondition, "获取用户信息失败"+err.Error())
			}
		}
		return nil, nil

	})
	return &u, nil
}
